import os
import shutil

import pytest

from config import config
from core import shell, consts, mail, log

if __name__ == '__main__':
    conf = config.Config()
    log = log.Log.get_logger()
    log.info('初始化配置文件，path' + conf.log_path)

    # 准备……
    shell = shell.Shell()
    xml_report_path = consts.XML_REPORT_PATH
    html_report_path = consts.HTML_REPORT_PATH
    case_path = consts.CASE_PATH
    # report_url_base = "http://192.168.1.36/PRAFrameworkPro68/"  # WAMP服务器中报告文件的URL基础路径
    report_url_base = f'http://{conf.get_wamp("url")}/PRAFrameworkPro68/'  # WAMP服务器中报告文件的URL基础路径

    # 定义测试集
    args = ['-s', '-q', '--alluredir', xml_report_path, case_path]
    pytest.main(args)

    # 生成报告
    cmd = 'allure generate {} -o {}'.format(xml_report_path, html_report_path)

    # 将报告部署到 WAMP
    report_folder_name = "allure_report"  # 实际存放报告的文件夹
    # report_destination = f"S:/APP/wampserver/wamp/www/PRAFrameworkPro68/{report_folder_name}"
    report_destination = f"{conf.get_wamp('www')}/PRAFrameworkPro68/{report_folder_name}"





    # 如果目标文件夹已存在，则先删除该文件夹
    if os.path.exists(report_destination):
        try:

            shutil.rmtree(report_destination)  # 删除已有的报告文件夹
            log.info(f"已删除旧的报告文件夹: {report_destination}")
        except Exception as e:
            log.error(f"删除旧报告文件夹失败: {e}")
            raise

    # 创建新的目标文件夹
    os.makedirs(report_destination, exist_ok=True)

    # 执行报告生成命令
    try:
        shell.execute(cmd)
    except Exception:
        log.error('执行用例失败，请检查环境配置')
        raise

    # 将报告文件夹从生成路径复制到目标路径
    try:
        shutil.copytree(html_report_path, report_destination, dirs_exist_ok=True)
        log.info(f"报告已成功复制到 WAMP 服务器：{report_destination}")
    except Exception as e:
        log.error(f"报告复制到 WAMP 失败: {e}")
        raise

    # 创建报告的 URL 地址
    report_url = f"{report_url_base}{report_folder_name}/index.html"

    # 发送邮件时将报告的 URL 地址放入邮件内容
    try:
        mail.send_email(report_url)
    except Exception as e:
        log.error(f'发送邮件失败，请检查邮件配置: {e}')
        raise
